package demo2;

public class LeetCode1314 {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int n1 = mat.length, n2 = mat[0].length;
        int[][] dp = new int[n1 + 1][n2 + 1];
        for (int i = 1; i <= n1; i++) {
            for (int j = 1; j <= n2; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }
        int[][] ans = new int[n1][n2];
        for (int i = 0; i < n1; i++) {
            for (int j = 0; j < n2; j++) {
                int x1 = Math.max(0, i - k) + 1;
                int x2 = Math.min(n1 - 1, i + k) + 1;
                int y1 = Math.max(0, j - k) + 1;
                int y2 = Math.min(n2 - 1, j + k) + 1;
                ans[i][j] = dp[x2][y2] - dp[x2][y1 - 1] - dp[x1 - 1][y2] + dp[x1 - 1][y1 - 1];
            }
        }
        return ans;
    }
}
